<template>
  <div>
    <a-modal
      v-model:open="visible"
      :mask-closable="false"
      width="40%"
      :title="title"
      :style="{ top: '20px' }"
      :footer="null"
    >
      <div v-if="visible" v-permission="['base-data:shop:modify']" v-loading="loading">
        <a-form
          ref="form"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 21 }"
          :model="formData"
          :rules="rules"
        >
          <a-form-item label="商品" name="productAll">
            <a-row>
              <a-col :span="24">
                <div style="padding-top: 5px">
                  <a-radio-group v-model:value="formData.productAll" name="productAllGroup">
                    <a-radio :value="true">全部商品</a-radio>
                    <a-radio :value="false">指定商品</a-radio>
                  </a-radio-group>
                </div>
              </a-col>
            </a-row>
            <a-row v-if="!formData.productAll">
              <a-col :span="24">
                <div style="padding-top: 5px" v-loading="productLoading">
                  <product-edit v-model:tableData="formData.products" />
                </div>
              </a-col>
            </a-row>
          </a-form-item>
          <div class="form-modal-footer">
            <a-space>
              <a-button type="primary" :loading="loading" html-type="submit" @click="submitForm"
                >保存</a-button
              >
              <a-button :loading="loading" @click="closeDialog">取消</a-button>
            </a-space>
          </div>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import * as api from '@/api/base-data/shop';
  import * as shopProductApi from '@/api/base-data/shop-product';
  import { SaveShopProductVo } from '@/api/base-data/shop-product/model/saveShopProductVo';
  import ProductEdit from '@/views/base-data/product/productEdit.vue';

  // 弹窗是否可见
  const visible = ref(false);
  // 加载中
  const loading = ref(false);
  // 商品加载中
  const productLoading = ref(false);
  // 弹窗标题
  const title = ref('授权商品');

  // 确认事件
  const emit = defineEmits(['confirm']);

  // 组件参数
  const props = defineProps({
    // 门店id
    shopId: {
      type: String,
      required: true,
    },
  });

  // 表单实例
  const form = ref();

  // 表单数据
  const formData = ref<SaveShopProductVo>({
    shopId: props.shopId,
    productAll: true,
    productIds: '',
    products: [],
  });

  // 表单验证规则
  const rules = ref({
    productAll: [
      { required: true, message: '请输入商品' },
      {
        validator: (rule, value, callback) => {
          if (!formData.value.productAll && !formData.value.products?.length) {
            callback(new Error('请输入商品'));
          } else {
            callback();
          }
        },
      },
    ],
  });

  // 打开弹窗
  const openDialog = () => {
    visible.value = true;
    initForm();
    loadShopData();
    loadShopProductData();
  };

  // 关闭弹窗
  const closeDialog = () => {
    visible.value = false;
  };

  // 初始化表单数据
  const initForm = () => {
    formData.value = {
      shopId: props.shopId,
      productAll: true,
      productIds: '',
      products: [],
    };
  };

  // 加载门店数据
  const loadShopData = async () => {
    loading.value = true;
    api
      .get(props.shopId)
      .then((data) => {
        formData.value.productAll = data.productAll;
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 加载商品数据
  const loadShopProductData = async () => {
    productLoading.value = true;
    shopProductApi
      .query({ pageIndex: 1, pageSize: 999, shopId: props.shopId })
      .then((data) => {
        formData.value.products = data.datas || [];
      })
      .finally(() => {
        productLoading.value = false;
      });
  };

  // 提交表单
  const submitForm = async () => {
    form.value.validate().then(() => {
      loading.value = true;
      shopProductApi
        .save({
          products: [],
          shopId: formData.value.shopId,
          productAll: formData.value.productAll,
          productIds: formData.value.products?.map((item) => item.productId).join(','),
        })
        .then(() => {
          emit('confirm');
          closeDialog();
        })
        .finally(() => {
          loading.value = false;
        });
    });
  };

  watch(
    () => formData.value.productAll,
    (newVal) => {
      if (newVal) {
        formData.value.productIds = '';
        formData.value.products = [];
      }
    },
  );

  defineExpose({
    openDialog,
  });
</script>

<style scoped></style>
